//
//  UIImage+Water.m
//  DCNativeApiPlugin
//
//  Created by iOSTean on 2022/6/7.
//

#import "UIImage+Water.h"
#import "WaterUtils.h"
#define kScreenWidth    [[UIScreen mainScreen] bounds].size.width
#define kScreenHeight   [[UIScreen mainScreen] bounds].size.height
#define LYFont(X) [UIFont fontWithName:@"Arial" size:X]
#define kStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] < 1 ? YES : NO )
@implementation UIImage (Water)
#pragma mark 添加水印
- (UIImage *_Nonnull)ly_addWatermarkWithWatermarkImages:(NSArray <UIImage *> *_Nullable)watermarkImages watermarkContents:(NSDictionary *)watermarkContents {
    CGFloat img_w = self.size.width;
    CGFloat img_h = self.size.height;
    CGFloat widthScale = img_w / kScreenWidth * 1.f;
    CGFloat heightScale = img_h / kScreenHeight * 1.f;
    CGFloat iconWidth = 18.0f * widthScale;
    CGFloat interval = 4.f * heightScale;
    CGFloat ori_X = 15.f * widthScale;
    UIColor *textColor = [WaterUtils sd_colorWithHexString:[watermarkContents valueForKey:@"color"] alpha:1];
    UIColor *rotatetextColor = [WaterUtils sd_colorWithHexString:[watermarkContents valueForKey:@"color"] alpha:0.4];
    UIFont *font = [UIFont fontWithName:@"Arial" size:[[watermarkContents valueForKey:@"fontSize"] floatValue] * widthScale];
    NSInteger iconType = [[watermarkContents valueForKey:@"iconType"] integerValue];
    @autoreleasepool {
        // 开启上下文
        UIGraphicsBeginImageContextWithOptions(self.size, NO, 1.f);
        // 绘制图片
        [self drawInRect:CGRectMake(0, 0, img_w, img_h)];
       
//        if([watermarkContents.allKeys containsObject:@"contents"] && [[watermarkContents valueForKey:@"contents"] isKindOfClass:[NSArray class]]){
//            
//            NSDictionary *attr = @{NSForegroundColorAttributeName:textColor, NSFontAttributeName:font};
////            初始底部y轴
//            CGFloat bottomY = img_h - 20.f * heightScale;
//            NSArray *arr = [watermarkContents valueForKey:@"contents"];
//            for (int i =0; i<arr.count; i++) {
//                NSDictionary *contentDict = arr[i];
//                NSString *text = [contentDict valueForKey:@"text"];
//                if(iconType == 1){
//                    text = [[NSString alloc] initWithFormat:@"• %@",text];
//                }
////                计算文字宽高
//                CGFloat textWidth = [WaterUtils stringWidth:text withFont:font];
//                textWidth = textWidth>img_w-2*ori_X?img_w-2*ori_X:textWidth;
//                CGFloat textHeight = [WaterUtils stringHeightWithString:text stringFont:font textWidth:textWidth];
//                CGRect textRect;
//                if(iconType == 2){
//                    textWidth = textWidth>self.size.width-2.0f*ori_X-iconWidth-5.f*widthScale?self.size.width-2.0f*ori_X-iconWidth-5.f*widthScale:textWidth;
//                    textHeight = [WaterUtils stringHeightWithString:text stringFont:font textWidth:self.size.width-2.0f*ori_X-iconWidth-5.f*widthScale];
//                    bottomY = bottomY-textHeight-2.5*interval;
//                    UIImage *locationImage = [WaterUtils converUniPath:[contentDict valueForKey:@"icon"]];
//                    CGRect iconRect = CGRectMake(ori_X,bottomY,iconWidth,iconWidth);
//                    textRect = CGRectMake(ori_X+iconWidth+5.f*widthScale,bottomY,textWidth,textHeight);
//                    [locationImage drawInRect:iconRect withContentMode:(UIViewContentModeScaleAspectFit) clipsToBounds:YES];
//                }else{
//                    bottomY = bottomY-textHeight-interval;
//                    textRect = CGRectMake(ori_X, bottomY, textWidth, textHeight);
//                }
//               
//                [text drawInRect:textRect withAttributes:attr];
//            }
//        }
        
        ///!!! 添加时间斜体水印
            NSString *waterText = [watermarkContents valueForKey:@"rotateText"];
            CGFloat horizontalSpace = 50.f * widthScale;// 水平间隔
            CGFloat vertivalSpace = 100.f * heightScale; // 竖直间隔
            NSDictionary *attributedDic =@{NSFontAttributeName:[UIFont systemFontOfSize:16 * widthScale], NSForegroundColorAttributeName:rotatetextColor};
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:waterText attributes:attributedDic];
            //绘制文字的宽高
            CGFloat strWidth = attrStr.size.width;
            CGFloat strHeight = attrStr.size.height;
            // 开始旋转上下文矩阵，绘制水印文字
            CGContextRef context = UIGraphicsGetCurrentContext();
            //将绘制原点（0，0）调整到源image的中心
            CGContextConcatCTM(context, CGAffineTransformMakeTranslation(img_w/2, img_h/2));
            //以绘制原点为中心旋转  (M_PI_2 / 3 ) <45>角度
            CGContextConcatCTM(context, CGAffineTransformMakeRotation(M_PI_2 / 3));
            //将绘制原点恢复初始值，保证当前context中心和源image的中心处在一个点(当前context已经旋转，所以绘制出的任何layer都是倾斜的)
            CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-img_w/2, -img_h/2));
            
            // 对角线
            CGFloat sqrtLength = sqrt(img_w*img_w + img_h*img_h);
            //计算需要绘制的列数和行数
            int horCount = sqrtLength / (strWidth + horizontalSpace) + 1;
            int verCount = sqrtLength / (strHeight + vertivalSpace) + 1;
            
            //此处计算出需要绘制水印文字的起始点，由于水印区域要大于图片区域所以起点在原有基础上移
            CGFloat orignX = -(sqrtLength-img_w)/2;
            CGFloat orignY = -(sqrtLength-img_h)/2;
            //在每列绘制时X坐标叠加
            CGFloat tempOrignX = orignX;
            //在每行绘制时Y坐标叠加
            CGFloat tempOrignY = orignY;
            for (int i = 0; i < horCount * verCount; i++) {
                [waterText drawInRect:CGRectMake(tempOrignX, tempOrignY, strWidth, strHeight) withAttributes:attributedDic];
                if (i % horCount == 0 && i != 0) {
                    tempOrignX = orignX;
                    tempOrignY += (strHeight + vertivalSpace);
                }else{
                    tempOrignX += (strWidth + horizontalSpace);
                }
            }
        
        UIImage *watermarkImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return watermarkImage;
    }
}
- (void)drawInRect:(CGRect)rect withContentMode:(UIViewContentMode)contentMode clipsToBounds:(BOOL)clips{
    CGRect drawRect = YYCGRectFitWithContentMode(rect, self.size, contentMode);
    if (drawRect.size.width == 0 || drawRect.size.height == 0) return;
    if (clips) {
        CGContextRef context = UIGraphicsGetCurrentContext();
        if (context) {
            CGContextSaveGState(context);
            CGContextAddRect(context, rect);
            CGContextClip(context);
            [self drawInRect:drawRect];
            CGContextRestoreGState(context);
        }
    } else {
        [self drawInRect:drawRect];
    }
}
CGRect YYCGRectFitWithContentMode(CGRect rect, CGSize size, UIViewContentMode mode) {
    rect = CGRectStandardize(rect);
    size.width = size.width < 0 ? -size.width : size.width;
    size.height = size.height < 0 ? -size.height : size.height;
    CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
    switch (mode) {
        case UIViewContentModeScaleAspectFit:
        case UIViewContentModeScaleAspectFill: {
            if (rect.size.width < 0.01 || rect.size.height < 0.01 ||
                size.width < 0.01 || size.height < 0.01) {
                rect.origin = center;
                rect.size = CGSizeZero;
            } else {
                CGFloat scale;
                if (mode == UIViewContentModeScaleAspectFit) {
                    if (size.width / size.height < rect.size.width / rect.size.height) {
                        scale = rect.size.height / size.height;
                    } else {
                        scale = rect.size.width / size.width;
                    }
                } else {
                    if (size.width / size.height < rect.size.width / rect.size.height) {
                        scale = rect.size.width / size.width;
                    } else {
                        scale = rect.size.height / size.height;
                    }
                }
                size.width *= scale;
                size.height *= scale;
                rect.size = size;
                rect.origin = CGPointMake(center.x - size.width * 0.5, center.y - size.height * 0.5);
            }
        } break;
        case UIViewContentModeCenter: {
            rect.size = size;
            rect.origin = CGPointMake(center.x - size.width * 0.5, center.y - size.height * 0.5);
        } break;
        case UIViewContentModeTop: {
            rect.origin.x = center.x - size.width * 0.5;
            rect.size = size;
        } break;
        case UIViewContentModeBottom: {
            rect.origin.x = center.x - size.width * 0.5;
            rect.origin.y += rect.size.height - size.height;
            rect.size = size;
        } break;
        case UIViewContentModeLeft: {
            rect.origin.y = center.y - size.height * 0.5;
            rect.size = size;
        } break;
        case UIViewContentModeRight: {
            rect.origin.y = center.y - size.height * 0.5;
            rect.origin.x += rect.size.width - size.width;
            rect.size = size;
        } break;
        case UIViewContentModeTopLeft: {
            rect.size = size;
        } break;
        case UIViewContentModeTopRight: {
            rect.origin.x += rect.size.width - size.width;
            rect.size = size;
        } break;
        case UIViewContentModeBottomLeft: {
            rect.origin.y += rect.size.height - size.height;
            rect.size = size;
        } break;
        case UIViewContentModeBottomRight: {
            rect.origin.x += rect.size.width - size.width;
            rect.origin.y += rect.size.height - size.height;
            rect.size = size;
        } break;
        case UIViewContentModeScaleToFill:
        case UIViewContentModeRedraw:
        default: {
            rect = rect;
        }
    }
    return rect;
}
#pragma mark - 压缩图片尺寸
+ (UIImage *_Nullable)newImageWithImage:(UIImage *_Nullable)image scaledToSize:(CGSize)newSize {
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0.f, 0.f, newSize.width, newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}
+ (UIImage *)imagesNamedFromCustomBundle:(NSString *)imgName{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"PictureWater" ofType:@"bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:path];
    NSString *img_path = [bundle pathForResource:imgName ofType:@"png"];
    return [UIImage imageWithContentsOfFile:img_path];
}
@end
